package com.zuiacsn.java_gobang.controller;

import com.zuiacsn.java_gobang.model.User;
import com.zuiacsn.java_gobang.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;


@RestController
public class UserController {

    @Autowired
    UserService userService;

    @PostMapping("/login")
    public User Login(String username, String password, HttpServletRequest request) {
        User user = userService.login(username, password);
        if(user.getUsername() != null){
            // 使用会话保存当前用户的信息
            // true 表示当前用户如果没有会话 可以创建一个新的会话
            HttpSession session = request.getSession(true);
            session.setAttribute("user",user);
        }
        return user; // 登录失败 返回空对象
    }

    @PostMapping("/register")
    public User register(String username, String password) {
        return userService.register(username, password);
    }

    /**
     * 获取登录用户信息
     * @param request
     * @return
     */
    @GetMapping("/userInfo")
    public Object getUserInfo(HttpServletRequest request){
        try {
            HttpSession session = request.getSession(false);
            User user =(User) session.getAttribute("user");
            return userService.selectByUserName(user.getUsername());
        } catch (NullPointerException e) {
            return new User();
        }
    }
}
